﻿(function () {
    /*
    *Author Kwan
    *Date 2010-11-22
    *Function jBase class
    */

    //check the class name , it will be replaced when existed
    if (window.Applican) {
        alert('variable jBase has been used,it will be replaced with _Applican!');
        window._Applican = window.Applican;
    }

    //constructor
    window.Applican = function (param) {
        param = param instanceof Object ? param : {};
        this.cfg = param.cfg || {};
    }
    var pt = Applican.prototype;

    $.fn.center = function () {
        var top = ($(window).height() - this.height()) / 2.5;
        var left = ($('body').innerWidth() - 120) / 2;
        var scrollTop = $(document).scrollTop();
        var scrollLeft = $(document).scrollLeft();
        return this.css({ position: 'absolute', 'top': top + scrollTop, left: left + scrollLeft }).show();
    }

    pt.limit = 20;
    pt.start = 0;
    pt.successCount = 0;
    pt.failCount = 0;
    pt.favsuccessCount = 0;
    pt.favfailCount = 0;
    pt.recordPositionY = 0;
    pt.ption = 320;

    pt.html = [];
    pt.html['SearchList'] = "<tr><td colspan='6' style='height:2px;'></td></tr>" +
"<tr class='tr0' bgcolor='#ffffff'>" +
    "<td class='td0'><input type='checkbox' name='check_XNumber' value='XNumber' ></td>" +
    "<td class='td1'><a href='/job/XNumber.html' class='jobname' target='_blank' >XJobName</a></td>" +
    "<td class='td2'><a href='/company/XCompanyID_1_10.html' class='coname' target='_blank' >XCompanyName</a></td>" +
    "<td class='td3'><span id='map_jobareaXNumber'>XCity</span></td>" +
    "<td class='td4'><span id='map_fbrqXNumber'>XIssuedate</span></td>" +
    "<td class='td5' valign='top'><div id='Appli_XNumber' onclick='app.appSingleJob(this);' class='btn_appjob' onmouseover=\"this.className='btn_appjobON'\" onmouseout=\"this.className='btn_appjob'\">立即申请</div></td>" +
"</tr><tr class='tr1'  bgcolor='#ffffff'>" +
    "<td class='td0'>&nbsp;</td>" +
    "<td colspan='4' class='td1234'>学历要求：XEducation&nbsp;&nbsp;|&nbsp;&nbsp;工作经验：XWorkYears &nbsp;&nbsp;|&nbsp;&nbsp;招聘人数：XEnrollments人</td>" +
    "<td class='td5'><div id='Fav_XNumber' onclick='app.favJob(this);' class='btn_favjob' onmouseover=\"this.className='btn_favjobON'\" onmouseout=\"this.className='btn_favjob'\">收藏</div><a id='Fav_XNumber' href='javascript:;' onclick='app.favJob(this);' style='color:#FF7300;'></td>" +
"</tr><tr class='tr2'  bgcolor='#ffffff'>" +
    "<td class='td0'>&nbsp;</td>" +
    "<td colspan='4' class='td1234 wordBreakNormal'>职位简介:<span >XDescription</span></td>" +
"</tr><tr class='tr3'><td colspan='6'></td></tr>";

    pt.Degree = ['不限', '初中', '高中', '中技', '中专', '大专', '本科', '硕士', '博士'];
    pt.Workyear = ['不限', '应届毕业生', '一年以上', '两年以上', '三年以上', '五年以上', '八年以上', '十年以上'];

    $(function () {
        $('#searchForm').submit(function () {
            pt.start = 0; pt.limit = 20;
            queryStr = decodeURI($("#searchForm").formSerialize());
            //queryStr = queryStr.replace(/%2C/g, ',');
            var options1 = {
                url: 'facade.axd',
                dataType: "json",
                data: { action: 'Job', start: pt.start, limit: pt.limit, s_method: 'list', query: queryStr },
                beforeSubmit: pt.beforeSubmit,
                success: pt.showResponse
                //complete: function(x) { $("#resultList").html(queryStr + "\r\n" + x.responseText); }
            };
            $('#searchForm').ajaxForm(options1);
            return false;
        });
    });

    pt.beforeSubmit = function (obj) {
        pt.loading();
    }

    pt.loading = function () {
        var div = $('<div id="tool_loading"><div class="loading"> 数据加载中,请稍后..</div></div>').appendTo('body');
        div.center();
    }
    pt.removeLoading = function () {
        $("#tool_loading").remove();
    }
    pt.t1 = '';
    pt.jumpp = function (page) {
        pt.t1 = new Date().getTime();
        queryStr = decodeURI(queryStr);
        pt.start = String(Number(page) * pt.limit - pt.limit);
        var options2 = {
            url: 'facade.axd',
            dataType: "json",
            data: { action: 'Job', start: pt.start, limit: pt.limit, s_method: 'list', query: queryStr },
            beforeSubmit: pt.beforeSubmit,
            success: pt.showResponse
            //complete: function(x) { $("#resultList").html(queryStr + x.responseText); }
        };
        $('#searchForm').ajaxSubmit(options2);
    }
    pt.AppJob = function (rid, jid) {
        var now = new Date();
        var nowDate = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " " + now.toLocaleTimeString();
        $.ajax({ url: "facade.axd", cache: false, dataType: "json", data: encodeURI("action=Applican&s_method=save&data={\"ResumeID\":\"" + rid + "\",\"JobID\":\"" + jid + "\",\"appDate\":\"" + nowDate + "\",\"State\":\"0\"}"),
            beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
            complete: function (x, state) {
                var json = eval("(" + x.responseText + ")");
                if (json.success) {
                    $.ajax({ url: "facade.axd", cache: false, dataType: "json", data: encodeURI("action=EmailSend&s_method=list&id=" + json.data),
                        beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }
                    });
                }
            }
        });
    }

    pt.checkJob = function (jid) {
        if (rid == "") {
            if (confirm("您还没有创建简历，现在创建吗？")) { window.location = "/Browser/MyXINJOB.aspx"; }
            return false;
        }
        $.ajax({ url: "facade.axd", cache: false, dataType: "json", data: "action=Applican&s_method=list&query=JobID=" + jid + "%26ResumeID=" + rid + "&limit=2",
            complete: function (x, state) {
                var json = eval("(" + x.responseText + ")");
                if (json.totalCount == 0) { pt.AppJob(rid, jid); pt.successCount++; } else { pt.failCount++; }
                redraw("<li style='text-align:center;'>成功申请 <font color='green'>" + pt.successCount + "</font> 个职位！申请失败 <font color='red'>" + pt.failCount + "</font> 次</li>");
                window.setInterval("FixPosition()", 1);
            }
        });
    }

    pt.appSingleJob = function (j) {
        if (typeof (uid) == "undefined" || uid == "Error" || uid == "") { alert('请登录后再申请职位！'); window.location = "/Login.aspx?returnUrl=%2fAdvanceSearch.aspx"; return false; }
        jid = j.id.replace('Appli_', '')
        this.checkJob(jid);
    }

    pt.applySelectedJobs = function () {
        if (typeof (uid) == "undefined" || uid == "Error" || uid == "") { alert('请登录后再申请职位！'); window.location = "/Login.aspx?returnUrl=%2fAdvanceSearch.aspx"; return false; }
        var jobArray = [];
        var chxs = document.getElementById('resultList').getElementsByTagName('input');
        var j = 0;
        for (var i = 0; i < chxs.length; i++) {
            if (/^check_/.test(chxs[i].name) && chxs[i].checked) {
                jobArray[j] = chxs[i].value;
                j++;
            }
        }
        if (jobArray.length == 0) { alert("请在要选择的职位前打勾！"); return; }
        for (var k = 0; k < jobArray.length; k++) {
            this.checkJob(jobArray[k]);
        }
    }
    pt.removeHtml = function (str) {
        //if (str == null) return '';
        str = str.replace(/<\/?.+?>/g, "");
        str = str.replace(/[ ]/g, "");
        str = str.replace(/\n|\r/g, "");
        //alert(str);
        return str.length > 200 ? str.substring(0, 200) + '...' : str;
    }
    pt.showResponse = function (responseText, statusText) {
        $("input[name='checkAll']").attr("checked", false);
        var str = ""; var pstr = ""; var totalCount = responseText.totalCount; var firstPage = 1; var thisPage = 1;
        if (totalCount > 0) {
            var jStr = "";
            var jHtml = pt.html['SearchList'];
            for (var i = 0; i < responseText.data.length; i++) {
                var Enrollments = responseText.data[i].Enrollments == '0' || responseText.data[i].Enrollments == null ? "若干" : responseText.data[i].Enrollments;
                jStr = jHtml;
                jStr = jStr.replace(/XUID/g, uid);
                jStr = jStr.replace(/XNumber/g, responseText.data[i].id);
                jStr = jStr.replace(/XCompanyID/g, responseText.data[i].CompanyID);
                jStr = jStr.replace(/XJobName/g, responseText.data[i].JobName);
                jStr = jStr.replace(/XCity/g, responseText.data[i].City);
                jStr = jStr.replace(/XIssuedate/g, responseText.data[i].EndDates);
                jStr = jStr.replace(/XEducation/g, pt.Degree[responseText.data[i].Degreefrom]);
                jStr = jStr.replace(/XWorkYears/g, pt.Workyear[responseText.data[i].Workyear]);
                jStr = jStr.replace(/XDescription/g, pt.removeHtml(responseText.data[i].Description));
                jStr = jStr.replace(/XCompanyName/g, responseText.data[i].CompanyName);
                jStr = jStr.replace(/XEnrollments/g, Enrollments);
                str += jStr;
            }
            var pageCount = Math.ceil(responseText.totalCount / pt.limit);
            $('#totalCount').html("共有职位 " + responseText.totalCount + " 个");
            if (pageCount > 0) {
                thisPage = pt.start / pt.limit + 1;
                var rightCount = pageCount - thisPage;
                var leftCount = thisPage - 1;
                var leftStr = ""; var rightStr = "";
                var pHtml = "<table  class='searchPageNav'><tr>XLeftXPagesXRight</tr></table>";
                //当前页右边页码
                if (pageCount <= thisPage) {    //当前页为最后一页
                    rightStr = "<td><img src='/Images/pageroff.gif' border='0' /></td>";
                }
                if (pageCount > thisPage) {     //当前页非最后一页
                    var rCount = rightCount > 4 ? 4 : rightCount; //当前页后面的页数
                    for (var r = thisPage + 1; r <= thisPage + rCount; r++) {
                        rightStr += "<td><a href='#" + r + "' class='orange1' onclick=app.jumpp(" + r + ") >" + r + "</a></td>";
                    }
                    rightStr += "<td><a href='#" + (thisPage + 1) + "' class='orange1' onclick='app.jumpp(" + (thisPage + 1) + ");' style='border:0px; width:auto;margin-left:5px;' ><img src='/Images/pageron.gif' border='0' /></a></td>";
                }
                //当前页左边页码
                if (thisPage <= firstPage) {    //当前页为第一页
                    leftStr = "<td style='padding-right:5px;' ><img src='/Images/pageloff.gif' border='0' /></td>";
                }
                if (thisPage > firstPage) {     //当前页非第一页
                    leftStr = "<td><a href='#" + (thisPage - 1) + "' class='orange1' onclick=app.jumpp(" + (thisPage - 1) + ") style='border:0px; width:auto;margin-right:5px;'><img src='/Images/pagelon.gif' border='0' /></a></td>";
                    var lCount = leftCount > 4 ? 4 : leftCount;  //当前页前面的页数
                    var beginPage = thisPage > 4 ? thisPage - 4 : 1;    //开始页码
                    for (var l = beginPage; l <= lCount + beginPage - 1; l++) {
                        leftStr += "<td><a href='#" + l + "' class='orange1' onclick=app.jumpp(" + l + ") >" + l + "</a></td>";
                    }
                }
                //替换代码
                pHtml = pHtml.replace(/XLeft/g, leftStr);
                pHtml = pHtml.replace(/XPages/g, "<td  class='currPage' >" + thisPage + "</td>");
                pHtml = pHtml.replace(/XRight/g, rightStr);
                //写入页面
                $("td[name='nav_page']").html(pHtml);
                //$("#nav_page").html(pHtml);
            }
            $("#resultList").html("<tr class='titleTr'><td  class='td0'>&nbsp;</td><td  class='td1'>职位名称</td><td  class='td2'>公司名称</td><td  class='td3'>工作地点</td><td  class='td4'>结束日期</td><td  class='td5'>&nbsp;</td></tr>" + str);
        }
        else {
            $("td[name='nav_page']").html("");
            $("span[name='totalCount']").html("共有职位 0 个");
            //$("#nav_page").html("");
            //$("#totalCount").html("共有职位 0 个");
            $("#resultList").html("<tr><td>暂无相关职位，请重新搜索！</td></tr>");
        }
        pt.removeLoading();
        //$(".loading").fadeOut();
        window.scrollTo(0, 0);
        //alert((new Date().getTime() - pt.t1) / 1000 + " 秒");
    }

    pt.favJob = function (jid) {
        jid = jid.id.replace('Fav_', '');
        $.ajax({ url: "facade.axd", cache: false, dataType: "json", data: "action=FavJob&s_method=list&query=JID=" + jid,
            complete: function (x, state) {
                var json = eval("(" + x.responseText + ")");
                if (json.totalCount == 0) {
                    $.ajax({ url: "facade.axd", data: encodeURI("action=FavJob&s_method=save&data={\"JID\":\"" + jid + "\"}") });
                    pt.favsuccessCount++;
                }
                else { pt.failCount++; }
                redraw("<li style='text-align:center;'>成功收藏 <font color='green'>" + pt.favsuccessCount + "</font> 个职位！收藏失败 <font color='red'>" + pt.favfailCount + "</font> 次</li>");
                window.setInterval("FixPosition()", 1);
            }
        });
    }

    pt.ftsearch = function (obj) {
        var index_id_arr = obj.id.split('_');
        $("input[name='" + index_id_arr[0] + "']").val(index_id_arr[1]);
        document.searchForm.submit();
    }

})();

window.app = new Applican();
window._ = app._;